package com.practice.Java中HttpClient如何使用;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

/**
 * @program: tenghw-practice-demo
 * @author: tenghw
 * @create: 2023-12-24 18:08
 * @Version 1.0
 * @description:
 **/
public class OkHttpDemo {
    private static final String url = "http://www.baidu.com";
    private static final OkHttpClient okClient=new OkHttpClient();
    //get请求
    public static void main0(String[] args) throws IOException {
        Request request = new Request.Builder()
                                     .url(url)
                                     .build();
        try(Response response = okClient.newCall(request).execute()){
            if(!response.isSuccessful()){
                System.out.println("服务器异常:"+response);
            }
            // 打印状态码
            System.out.println("响应状态码:"+response.code());//200
            // 打印响应体
            System.out.println(response.body().string());
        }
    }

    //post请求
    public static void main(String[] args) throws IOException {
        // 创建POST请求体
        FormBody formBody = new FormBody.Builder()
                .add("wd", "韩信")
                .add("age", "18")
                .add("key1", "value1")
                .build();
        // 创建POST请求
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        try(Response response = okClient.newCall(request).execute()){
            if(!response.isSuccessful()){
                System.out.println("服务器异常:"+response);
            }
            // 打印状态码
            System.out.println("响应状态码:"+response.code());
            // 打印响应体
            System.out.println(response.body().string());
        }
    }
}